#!/usr/bin/env python


__version__ = "0.4.1"

from winFTP import winFtp
from outDir import outDir

# example helloworld.py

import pygtk
pygtk.require('2.0')
import gtk
import gobject
import os.path
import subprocess
import pprint
import winFTP
import os
import sys
import ConfigParser

class PyScreenshot:
    
    
    icon_file = 'camera.png'


    def delete_event(self, widget, event, data=None):
        # If you return FALSE in the "delete_event" signal handler,
        # GTK will emit the "destroy" signal. Returning TRUE means
        # you don't want the window to be destroyed.
        # This is useful for popping up 'are you sure you want to quit?'
        # type dialogs.
        print "delete event occurred"
        # Change FALSE to TRUE and the main window will not be destroyed
        # with a "delete_event".
        self.window.hide()
        return True

    def destroy(self, widget, data=None):
        print "destroy signal, bye motherfucker"
        gtk.main_quit()

    def __init__(self):
        
        
        self.app_title = 'pyscreenshot'
        
        self.get_app_configs()
        
        self.win_setting_file = self.app_config_dir + '/winsettings.ini'
        self.win_setting_config = ConfigParser.ConfigParser()
        self.win_setting_config.read( self.win_setting_file )
        
        # create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_size_request(400, 500)
        self.window.set_position(gtk.WIN_POS_CENTER)
        #self.window.set_border_width(10)
        self.window.set_title(self.app_title)
        
        icon_path = os.path.dirname(sys.argv[0]) + '/' + self.icon_file
        if os.path.dirname(sys.argv[0]) == '':
            icon_path = self.icon_file
        else:    
            icon_path
        print icon_path
        self.window.set_icon_from_file( icon_path )
    
        self.window.connect("delete_event", self.delete_event)
        #self.window.connect("destroy", self.destroy) // to remove
    
    
        # START
        self.buttonStart = gtk.Button("Screenshot")
        self.buttonStart.show()
        self.buttonStart.connect("clicked", self.create_screenshot_start)
    
        list = self.create_list()
        
        
        self.entryFileName = gtk.Entry()
        self.entryFileName.show()
        
        # pack_start(child, expand=True, fill=True, padding=0)
        box = gtk.VBox()
        self.window.add(box)
        
        # MAIN MENU
        self.get_main_menu()
        self.mmenu.show()
        box.pack_start(self.mmenu, False, False, 0)
        
        # Frame name
        frameFileName = gtk.Frame(" New image file name ")
        frameFileName.show()
        frameFileName.add( self.entryFileName )
        
        
        
        # poziome
        hbox1 = gtk.HBox()
        hbox1.pack_start(frameFileName,  True, True, 0)
        hbox1.pack_start(self.buttonStart, False, False, 0)
        
        hbox2 = gtk.HBox()
        
        self.labelCounter = gtk.Label('3')
        self.labelCounter.set_text('5')
        #self.labelCounter.show()
        
        hbox2.pack_start(self.labelCounter, False, False, 0)
        
        # DELAY 
        adj = gtk.Adjustment(0.0, 0.0, 59.0, 1.0, 5.0, 0.0)
        self.spinbutton1 = gtk.SpinButton(adj, climb_rate=0.0, digits=0)
        self.spinbutton1.set_value(3)
	try:
        	self.spinbutton1.set_value( float( self.win_setting_config.get('general', 'delay') ) )
	except ConfigParser.NoSectionError:
		print "no config" #TODO
        
        
        self.spinbutton1.show()
        self.spinbutton1.set_range(0,60)
        self.spinbutton1.set_numeric(True)
        
        frameDelay = gtk.Frame(" Delay ")
        frameDelay.show()
        frameDelay.add( self.spinbutton1 )
        hbox2.pack_start(frameDelay, False, False, 0)
        
        # OUT DIR
        storeOutdir = gtk.ListStore(gobject.TYPE_STRING)
        try:
            fileO = open(self.app_config_dir + '/outdir.list', "r")
        except IOError:
            fileO=False
        if fileO:
            line = fileO.readlines()
            for l in line:
                storeOutdir.append ([l.replace( "\n", "" )])
        else:
            storeOutdir.append (["/tmp"])
            
        
         
        
        self.combobox1Out = gtk.ComboBoxEntry()
        self.combobox1Out.set_model(storeOutdir)
        self.combobox1Out.set_text_column(0)
        self.combobox1Out.set_active(0)
	try:
        	self.combobox1Out.set_active( int(self.win_setting_config.get('general', 'output_dir')) )
	except ConfigParser.NoSectionError:
        	print "no config" #TODO
        
        
        
        frameOut = gtk.Frame(" Output dir ")
        frameOut.show()
        frameOut.add( self.combobox1Out )
        
        hbox2.pack_start(frameOut, True, True, 0)
        self.combobox1Out.show()
        
        
        box.pack_start( hbox1, False, False, 0 )
        box.pack_start( hbox2, False, False, 0 )
        
        
        # FTP expander
        if self.ftp_data != False:
            expander = gtk.Expander("FTP Url")
            box.pack_start(expander, False, False, 0)
            expander.show()        
            self.entryUrl = gtk.Entry()
            self.entryUrl.show()
            expander.add(self.entryUrl)
        
        
        
        # LIST and IMAGE
        self.vpaned1 = gtk.VPaned()
        self.image_area()
        self.scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)        
        self.vpaned1.add1(list)
        self.vpaned1.add2(self.scrolled_window)
        self.scrolled_window.show()
        box.pack_start(self.vpaned1)
        self.vpaned1.show()
        
        list.show()
        box.show()
        hbox1.show()
        hbox2.show()
        self.entryFileName.show()
        # and the window
        self.timer_id = None
        self.window.show()
        self.tray = TrayIcon(self)

        
    def add_to_list(self, widget):
        pass    
        print 'list'
        self.create_screenshot()
        return False
        name = self.entryFileName.get_text()
        el = self.model.insert(0)
        self.model.set(el, 0, name)
      
    
        
    def create_screenshot_start(self, widget):
        self.labelCounter.set_text(self.spinbutton1.get_text())
        self.timer_id = gobject.timeout_add(1000, self.update_clock)
        
        
    def create_screenshot(self):
        print "create_screenshot"
    
        name = self.entryFileName.get_text()
        
        if len(name)<1:
            md = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE, "File name is empty")
            md.run()
            md.destroy()
            return False
    
        name =  name.replace(" ", "_")
        outDir = self.combobox1Out.get_active_text()
        print outDir
        if not os.path.exists(outDir):
            md = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE, "Output dir not exist")
            md.run()
            md.destroy()
            return False
        
        import_outfile = os.path.realpath(outDir) + "/" + name + ".png"
        
        
        self.timer_id = None
        
        
        process = subprocess.Popen(['import', import_outfile], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while process.poll() is None:
            out = process.stdout.readline()
            print "# " + out
        
        el = self.model.insert(0)
        self.model.set(el, 0, import_outfile)
        self.window.set_title( str( self.app_title ) ) # TODO not working
        
        
             
    def update_clock(self):
        if self.timer_id is not None:
            seconds = self.labelCounter.get_text()
            if len(seconds):
                seconds = int(seconds)
            else:
                seconds = 0
            if seconds < 2:
                gobject.source_remove(self.timer_id)
                self.timer_id = None
                print 'GOOOOOO'
                self.create_screenshot()
                # stopppppp    
            
            seconds = seconds + -1
            self.labelCounter.set_text(str(seconds))
            self.window.set_title( "[ " + str(seconds) + " ] " + str( self.app_title ) )
            return True # run again in one second
        return False # stop running again
    
    def create_list(self):
        # Create a new scrolled window, with scrollbars only if needed
        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)

        self.model = gtk.ListStore(gobject.TYPE_STRING)
        self.tree_view = gtk.TreeView(self.model)
        
        #self.tree_view.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        self.tree_view.set_events(gtk.gdk.BUTTON_PRESS_MASK)
        
        
        self.tree_view.connect('button-press-event', self.on_treeview_button_press_event)
        
        # @TODO 13.48. How do I hide some rows in a TreeView? 
        # http://faq.pygtk.org/index.py?req=show&file=faq13.048.htp
        
        # How do I delete the selected rows in a TreeView?
        # http://faq.pygtk.org/index.py?req=show&file=faq13.008.htp
        
        # How do I make a popup menu appear when I right-click my TreeView?
        # http://faq.pygtk.org/index.py?req=show&file=faq13.017.htp
        
        #self.tree_view.connect("row-activated", self.on_activated_tree_view)
        #self.tree_view.connect("expand-collapse-cursor-row", self.on_activated_tree_view_one_click)
        #self.tree_view.connect("row-activated", self.on_activated_tree_view_one_click2)
        #self.tree_view.connect("cursor-changed", self.on_activated_tree_view_one_click)
        
        
        selection = self.tree_view.get_selection()
        selection.connect('changed', self.on_activated_tree_view_one_click)
        #self.tree_view.get_selection().connect("changed", self.on_activated_tree_view_one_click)
        
        scrolled_window.add_with_viewport (self.tree_view)
        self.tree_view.show()

        # Add some messages to the window
        #for i in range(4):
        #    msg = "Message #%d" % i
        #    iter = self.model.append()
        #    self.model.set(iter, 0, msg)

        #iter = self.model.append()
        #self.model.set(iter, 0, "/home/tomek/smieci/zrzuty/screenshot_100203132459_calc3.png")
        #iter = self.model.append()
        #self.model.set(iter, 0, "/tmp/b.png")

        cell = gtk.CellRendererText()
        column = gtk.TreeViewColumn("Messages", cell, text=0)
        self.tree_view.append_column(column)
   
        #self.tree_view.add_events(gtk.gdk.BUTTON_PRESS_MASK )
        #self.tree_view.connect('button_press_event', self.list_click)
        
        # POPUP
        self.get_popup_menu()
        
        return scrolled_window
    
    
    def get_popup_menu(self):
        print 'popup'
        self.pmenu = gtk.Menu()
        menu_gimp = gtk.MenuItem('Open with gimp')
        self.pmenu.append(menu_gimp)
        menu_gimp.connect("activate", self.popup_menu_run_gimp)
        
        menu_gthumb = gtk.MenuItem('Open with gthumb')
        self.pmenu.append(menu_gthumb)
        menu_gthumb.connect("activate", self.popup_menu_run_gthumb)

        if self.ftp_data != False and len(self.ftp_data) > 0:
	    #print self.ftp_data	
	    #print len(self.ftp_data)	
            menu_ftp = gtk.MenuItem('Send to FTP ('+ self.ftp_data['name'] +')')
            self.pmenu.append(menu_ftp)
            menu_ftp.connect("activate", self.popup_menu_run_ftp)
        
        self.pmenu.show_all()
    
    def popup_menu_run_gimp(self, widget):
        selection = self.tree_view.get_selection()
        (model, iter) = selection.get_selected()
        jid = model.get_value(iter, 0)
        process = subprocess.Popen(['gimp', jid], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    def popup_menu_run_gthumb(self, widget):
        selection = self.tree_view.get_selection()
        (model, iter) = selection.get_selected()
        jid = model.get_value(iter, 0)
        process = subprocess.Popen(['gthumb', jid], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        
    def popup_menu_run_ftp(self, widget):
        selection = self.tree_view.get_selection()
        (model, iter) = selection.get_selected()
        jid = model.get_value(iter, 0)
        print self.get_ftp_command( jid )
        
        #process = subprocess.Popen([self.get_ftp_command(jid), jid], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    def get_ftp_config(self):
        pass
        # self.config    
        #self.configFtp.get(section, option)
        
        self.ftp_data={}
        if self.configFtp.has_option("ftp", "name"):
            self.ftp_data["name"] = self.configFtp.get("ftp", "name")
        else:
            return False
        
        if self.configFtp.has_option("ftp", "host"):
            self.ftp_data["host"] = self.configFtp.get("ftp", "host")
        else:
            return False
        
        if self.configFtp.has_option("ftp", "user"):
            self.ftp_data["user"] = self.configFtp.get("ftp", "user")
        else:
            return False
        
        if self.configFtp.has_option("ftp", "pass"):
            self.ftp_data["pass"] = self.configFtp.get("ftp", "pass")
        else:
            return False
        
        if self.configFtp.has_option("ftp", "path"):
            self.ftp_data["path"] = self.configFtp.get("ftp", "path")
        else:
            return False
        
        if self.configFtp.has_option("ftp", "url"):
            self.ftp_data["url"] = self.configFtp.get("ftp", "url")
        else:
            return False
        
        return True
        
        
        
    def get_ftp_command(self, path):

        namepos = path.rfind('/')
        basename = path[(namepos+1):]
        dirname = path[:namepos]
        
        ftp = ""
        ftp += "cd " + dirname + "; "
        ftp += "ftp -n -v -p "+ self.ftp_data['host'] +" <<EOT\n"
        ftp += "ascii\n"
        ftp += "user "+ self.ftp_data['user'] + " " + self.ftp_data['pass'] + "\n"
        ftp += "prompt\n"
        ftp += "cd " + self.ftp_data['path'] + "\n"
        ftp += "put " + basename + "\n"
        ftp += "bye\n"
        ftp += "EOT\n"
        
        process = subprocess.Popen(["xterm", "-title", "Sending: " + basename , "-hold", "-e", ftp], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        #process = subprocess.Popen(["xterm", "-hold", "-e", "file", path], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return process
        
    
            
        
    def popup_menu_run(self, widget):
        pass
        pprint.pprint(widget)
        #print widget.get_active()
        print 'popup_menu_run'
        
    
    def on_activated_tree_view_right_click(self, widget):
        pass
        print 'RIGHT!!!'
        
        
        
    def on_treeview_button_press_event(self, treeview, event):
        #print 'on_treeview_button_press_event on_treeview_button_press_event on_treeview_button_press_event'
        if event.button == 3:
            #print 'PRAWYY'
            x = int(event.x)
            y = int(event.y)
            time = event.time
            pthinfo = treeview.get_path_at_pos(x, y)
            if pthinfo is not None:
                #pprint.pprint(pthinfo)
                path, col, cellx, celly = pthinfo
                treeview.grab_focus()
                treeview.set_cursor( path, col, 0)
                self.pmenu.popup( None, None, None, event.button, time)
            return True
        
    def on_activated_tree_view_one_click2(self,  event):
        if event.button == 3:
            print 'PPPP22222222'
        
        
    def on_activated_tree_view_one_click(self, widget, event=False):
        
        #print self.tree_view.get_events()
        #print self.tree_view.event().get()
        #print "Event number %d woke me up" % event.type
        #print event
        
        selection = self.tree_view.get_selection()
        #pprint.pprint(selection)
        (model, iter) = selection.get_selected()
        jid = model.get_value(iter, 0)
        #print jid
        self.image.set_from_file( jid )
        self.image.show()
        
        url = jid.rfind("/")
        
        self.entryUrl.set_text( 'http://' + self.ftp_data['url'] + jid[(url):] )
        #self.entryUrl.set_text(jid)
        

    # nieuzwana, na 2click
    def on_activated_tree_view(self, widget, row, col):
        model = widget.get_model()
        #text = model[row][0] + ", " + model[row][1] + ", " + model[row][2]
        text = model[row][0] + " ## "
        print text
    
    def list_click(self, widget, event):
        #print "cccccccccc"
        if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
            print 'left double click'

        if event.button == 1 and event.type == gtk.gdk.BUTTON_PRESS:
            print 'left ONE click'
    
        if event.button == 1:
            print "left click"
    
        treeselection = self.tree_view.get_selection()
        #print treeselection 
        (model, iter) = treeselection.get_selected()
        print iter
        name_of_data = model.get_value(iter, 0)
        print name_of_data
    
    def image_area(self):
        self.scrolled_window = gtk.ScrolledWindow()
        self.scrolled_window.set_border_width(10)        
        self.image = gtk.Image()
        self.image.set_from_file("/home/tomek/smieci/zrzuty/zrzut_100112124023_t2.png")
        self.image.show()
        self.scrolled_window.add_with_viewport(self.image)
        
        
    def open_window_ftp(self, widget):
            winFtp(self)

    def open_window_outdir(self, widget):
            outDir(self)
        
    def get_main_menu(self):
        
        self.mmenu = gtk.MenuBar()
        filemenu = gtk.Menu()
        
        filem = gtk.MenuItem("File")
        filem.set_submenu(filemenu)
        exit = gtk.MenuItem("Exit")
        exit.connect("activate", self.on_exit)
        filemenu.append(exit)
        
        ftp = gtk.MenuItem("Ftp settings")
        ftp.connect("activate", self.open_window_ftp)
        
        out = gtk.MenuItem("Output dirs")
        out.connect("activate", self.open_window_outdir)
        
        setingsMenu =  gtk.Menu()
        setingsm = gtk.MenuItem("Settings")
        setingsm.set_submenu(setingsMenu)
        setingsMenu.append(out)
        setingsMenu.append(ftp)
        
        helpMenu =  gtk.Menu()
        helpM = gtk.MenuItem("Help")
        helpM.set_submenu(helpMenu)
        aboutM = gtk.MenuItem("About")
        aboutM.connect("activate", self.on_about)
        helpMenu.append(aboutM)
        
        
        self.mmenu.append(filem)
        self.mmenu.append(setingsm)
        self.mmenu.append(helpM)
        self.mmenu.show_all()
        
    def on_about(self, data):
        global __version__
        dialog = gtk.AboutDialog()
        dialog.set_name('pyScreenshot')
        dialog.set_version(__version__)
        dialog.set_comments('Screenshot tool in pyGtk')
        dialog.set_website('http://code.google.com/p/pyscreenshot')
        dialog.run()
        dialog.set_position(gtk.WIN_POS_CENTER)
        dialog.destroy()
        
        
    def get_app_configs(self):
        if os.uname()[0] != 'Linux':
            print 'only in Linux';
            md = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE, "Sorry. I'm working only in Linux OS")
            md.run()
            md.destroy()
            gtk.main_quit()
        self.app_config_dir = os.path.expanduser('~')+'/.pyscreenshot'
        if not os.path.isdir(self.app_config_dir):
            print 'Creating app dir: ' + self.app_config_dir;
            os.mkdir(self.app_config_dir)
            
        if os.path.isfile(self.app_config_dir + '/' + 'pyscreenshot.ini0'):    
            self.configMain = ConfigParser.ConfigParser()
            self.configMain.read(self.app_config_dir + '/' + 'pyscreenshot.ini0')
            #print int(self.configMain.get("general", "from"))
        
        self.configFtp = ConfigParser.ConfigParser()
        configFtpFile = self.app_config_dir + '/ftp.ini'
        self.configFtp.read( configFtpFile )
        
        if self.get_ftp_config() == True:
            # add ftp support
            print 'ftp ok'
            #print self.ftp_data
         
    def on_exit(self, widget):
        #global _ini
        #self.config.set('general', 'from', self.combo.get_active())
        #self.config.set('general', 'to', self.combo2.get_active())
        #self.config.write(open(_ini, 'w'))
        #gc.collect()
        self.win_settings_save()
        gtk.main_quit()           

    def win_settings_save(self):
        try:
            self.win_setting_config.set('general', 'output_dir', self.combobox1Out.get_active())
        except ConfigParser.NoSectionError:
            self.win_setting_config.add_section('general')
            self.win_setting_config.set('general', 'output_dir', self.combobox1Out.get_active())
        self.win_setting_config.set('general', 'delay', self.spinbutton1.get_text())
        self.win_setting_config.write(open(self.win_setting_file, 'w'))
        
    
    def win_settings_get(self):
        pass
    

    def main(self):
        gtk.main()


class TrayIcon(gtk.StatusIcon):
    def __init__(self, parent):
        global _icon
        self.parent = parent
        gtk.StatusIcon.__init__(self)
        
        self.get_tray_menu()
        
        self.connect('popup-menu', self.on_popup_menu)
        self.connect('activate', self.on_active)
        
        #md = gtk.MessageDialog(self.parent.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE, os.path.dirname(sys.argv[0]) )
        #md.run()
        #md.destroy()
        
        #self.set_from_file( os.path.dirname(sys.argv[0]) + '/' + 'camera.png')
        
        icon_path = os.path.dirname(sys.argv[0]) + '/' + self.parent.icon_file
        if os.path.dirname(sys.argv[0]) == '':
            icon_path = self.parent.icon_file
        
        
        #self.set_from_file( os.path.dirname(sys.argv[0]) + '/' + self.parent.icon_file)
        self.set_from_file( icon_path )
        self.set_tooltip('Punks Terror')
        self.set_visible(True)
        
        
        

    def on_popup_menu(self, status, button, time):
        self.pmenu.popup(None, None, None, button, time)
        #self.parent.pmenu.popup(None, None, None, button, time)

    def on_active(self, data):
        if self.parent.window.get_property('visible'): self.parent.window.hide()
        else: self.parent.window.show_all()    
        
    def get_tray_menu(self):
        self.pmenu = gtk.Menu()
        menu_gimp = gtk.MenuItem('Exit')
        self.pmenu.append(menu_gimp)
        menu_gimp.connect("activate", self.parent.on_exit)
        
        menu_gthumb = gtk.MenuItem('Take screenshot')
        self.pmenu.append(menu_gthumb)
        menu_gthumb.connect("activate", self.on_take_screenshot)        
        self.pmenu.show_all()

    
    def on_take_screenshot(self, data):
        pass
        print 'on_take_screenshot'

if __name__ == "__main__":
    pys = PyScreenshot()
    pys.main()
